package com.yuzhihao.writejvm.code.g;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.code.Operation;
import com.yuzhihao.writejvm.code.StackFrame;
import com.yuzhihao.writejvm.format.FormsEnum;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import com.yuzhihao.writejvm.read.Parses;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;

/**
 * goto
 * @author yzh
 * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.goto">jvmdoc</a>
 * @since 2021年12月16日15:32:03
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Log4j2
public class Goto extends Operation implements Parses {

    private FormsEnum fe = FormsEnum.goto_;

    private ClassInfo ci;

    private int indexbyte1;

    private int indexbyte2;

    private int gotoindex;

    @Override
    public StackFrame exec(StackFrame frame) {

        return frame;
    }



    @Override
    public int parse(DataInputStream dis, ClassInfo ci) {
        this.setCi(ci);
        try {
            this.indexbyte1 = Parse.byteToInt(1, dis);
            this.indexbyte2 = Parse.byteToInt(1, dis);
            this.gotoindex =  (indexbyte1 << 8) | indexbyte2;
        } catch (IOException e) {
            log.error(e);
        }
        return 1+1;
    }

    @Override
    public String print(String print) {
        StringBuilder builder = new StringBuilder();
        builder.append(print).append(PrintFormat.EMPTY)
                .append(super.index).append(PrintFormat.COLON)
                .append(PrintFormat.EMPTY).append(fe.name());

        while (builder.length() < PrintFormat.EMPTY_20){
            builder.append(PrintFormat.EMPTY);
        }
        builder.append(this.gotoindex).append(System.lineSeparator());

        return builder.toString();
    }

}
